const app = getApp();
Page({
  data: {
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,
    towerUrl: app.globalData.towerUrl,
    currentDate: '',
    currentTime: '',
    checkInButtonLabel: '打卡',
    checkInStatus: '',
    longitude: '',
    latitude: '',
    targetLat: '',
    targetLon: '',
    location: '',
    lineName: '',
    imgList: [],
    id: '',
    distanceConf:'',
    imgSuccessLoaded: [],
    curUser:wx.getStorageSync('userinfo').siocCnName,
  },
  onLoad: function (options) {
    this.getLocation();
    this.getTarLocation(options.id);
    this.updateDateTimeInterval();
    this.getDistanceConf();
    this.setData({
      id: options.id
    })
  },
  getTarLocation: function (id) {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/patrolLocation/wx/getLocationById?id=' + id,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头
      },
      success(res) {
        console.log('获取巡更地点结果:', res.data);
        var data = res.data;
        if (200 != data.code) {
          wx.showModal({
            title: '提示',
            content: data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/login/index'
                })
              }
            }
          })
        } else {
          that.setData({
            targetLon: data.data.longitude,
            targetLat: data.data.latitude,
            location: data.data.location,
            lineName: data.data.lineName
          })
        }
      }
    });
  },
  updateDateTime: function () {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    this.setData({
      currentDate: `${year}-${month}-${day}`,
      currentTime: `${hours}:${minutes}:${seconds}`
    });
  },
  checkIn: function () {
      // 这里可以添加打卡的逻辑，比如更新状态、存储记录等
      this.setData({
        checkInStatus: '打卡成功',
        checkInButtonLabel: '已打卡',
        // 如果需要存储历史记录，可以添加到checkInHistory数组中
        // checkInHistory: [...this.data.checkInHistory, { date: this.data.currentDate, time: this.data.currentTime }]
      });
      // 可以使用wx.setStorageSync存储打卡记录到本地，或者使用wx.request发送到服务器
      wx.showToast({
        title: '打卡成功',
        icon: 'success',
        duration: 2000
      });
      // 重置打卡状态（可选，根据需求决定是否需要）
      // 可以设置一个定时器，在一段时间后自动重置状态或按钮标签
      setTimeout(() => {
        this.setData({
          checkInStatus: '',
          checkInButtonLabel: '打卡'
        });
      }, 3600000); // 1小时后重置（示例值，根据实际需求调整）
    }
    // 如果需要定期更新日期和时间，可以添加一个定时器在onLoad中启动
    ,
  onUnload: function () {
    clearInterval(this.dateTimeInterval); // 页面卸载时清除定时器
  },
  updateDateTimeInterval: function () {
    this.dateTimeInterval = setInterval(() => {
      this.updateDateTime();
    }, 1000); // 每秒更新一次（示例值，根据实际需求调整）
  },
  getLocation: function () {
    const that = this;
    wx.getLocation({
      type: 'gcj02', // 返回可以用于 `wx.openLocation` 的经纬度
      success(res) {
        console.log('当前位置：', res);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      },
      fail(err) {
        console.error('获取位置失败：', err);
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
      }
    });
  },
  setLocation: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/patrolLocation/wx/update',
      method: 'POST',
      data: {
        id : that.data.id,
        latitude : that.data.latitude,
        longitude : that.data.longitude,
        updateBy: that.data.curUser,
      },
      success: function (res) {
        console.log('表单提交成功', res);
        if(200 == res.data.code){
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            // success: function (res) {
            //   if (res.confirm) {
            //     wx.reLaunch({
            //       url: '/pages/check-item/check-item?itemId=' + that.data.itemId
            //     })
            //   }
            // }
          });
        }else{
          wx.showToast({
          title: '提交失败',
          icon: 'none'
        });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },

  checkDistance: function () {
    const targetLat = this.data.targetLat;
    const targetLon = this.data.targetLon;
    const currentLat = this.data.latitude;
    const currentLon = this.data.longitude;
    const R = 6371e3; // 地球半径，单位为米

    if(!targetLat || !targetLon){
      return true;
    }

    const dLat = (currentLat - targetLat) * Math.PI / 180;
    const dLon = (currentLon - targetLon) * Math.PI / 180;

    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(targetLat * Math.PI / 180) * Math.cos(currentLat * Math.PI / 180) *
      Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c; // 计算出的距离，单位为米

    console.log('距离：', distance, '米');
    return distance <= this.data.distanceConf; // 判断是否在范围内
  },

  daka: function () {
    const isWithinRange = this.checkDistance();
    if (isWithinRange) {
      //弹窗输入情况
      wx.showModal({
        editable: true, //显示输入框
        placeholderText: '输入巡检情况', //显示输入框提示信息
        success: res => {
          if (res.confirm) { //点击了确认
            var errMsg = "";
            console.log(res.content) //用户输入的值
            if(!res.content){
              errMsg = errMsg + "巡检情况不能为空;";
            }
            if (this.data.imgList.length < 1) {
              errMsg = errMsg + "巡检图片不能为空;";
            }
            if(errMsg.length > 0){
              wx.showModal({
                title: '提示',
                content: errMsg,
                showCancel: false
              })
              return;
            }
            // 向服务器提交表单数据
            var that = this;
            wx.request({
              url: that.data.baseUrl + '/patrolRecord/wx/add',
              method: 'POST',
              data: {
                createBy: that.data.curUser,
                location: that.data.location,
                lineName: that.data.lineName,
                imgList: that.data.imgList,
                remark: res.content,
                locationId: that.data.id
              },
              success: function (res) {
                wx.hideLoading()
                console.log('表单提交成功', res);
                if (200 == res.data.code) {
                  wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        wx.navigateTo({
                          url: '/pages/login/index'
                        })
                      }
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                  });
                }
              },
              fail: function (err) {
                wx.hideLoading()
                console.error('表单提交失败', err);
                wx.showToast({
                  title: '表单提交失败',
                  icon: 'none'
                });
              }
            });
          } else {
            console.log('用户点击了取消')
          }
        }
      })
    } else {
      wx.showToast({
        title: '不在打卡范围内',
        icon: 'none'
      });
    }
  },
  ViewImage(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    for (let key in this.data.imgList) {
      urls.push(this.data.fileUrl + this.data.imgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.data.imgSuccessLoaded.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList,
            imgSuccessLoaded: this.data.imgSuccessLoaded
          })
        }
      }
    })
  },
  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      async success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.imgList.length != 0) {
              that.setData({
                imgList: that.data.imgList.concat(tempArray)
              })
            } else {
              that.setData({
                imgList: tempArray
              })
            }
          }
        })
      }
    })
  },

  imageLoad(e) {
    this.data.imgSuccessLoaded.push(1)
    this.setData({
      imgSuccessLoaded: this.data.imgSuccessLoaded
    })
  },

  imageError(e) {
    this.data.imgSuccessLoaded.push(0)
    this.setData({
      imgSuccessLoaded: this.data.imgSuccessLoaded
    })
  },
  getDistanceConf() {
    var that = this;
    wx.request({
      url: that.data.towerUrl + '/api/tower/moa/wx/getEnumsByKey?key=patrol_distance',
      method: 'POST',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取距离配置:', res.data);
        that.setData({
          distanceConf: res.data.data[0].keyValue
        })
      }
    });
  },
});